import 'package:flutter/material.dart';

// RefreshIndicator 下拉刷新
// ListView 垂直列表
// ScrollController 上拉加载更多

const TextStyle textStyle = TextStyle(
  fontSize: 18,
  // fontWeight: FontWeight.bold,
);

class CommonLoadingButton extends StatelessWidget {
  // 加载状态
  final bool loadingState;

  // 是否有更多
  final bool hasMore;

  // 默认构造函数
  CommonLoadingButton({Key key, this.loadingState, this.hasMore})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 60,
      alignment: Alignment.center,
      child: Text(
        this.hasMore
            ? (this.loadingState ? 'This is loading' : 'load static')
            : 'This is empty',
        style: textStyle,
      ),
    );
  }
}

class RefreshPage extends StatefulWidget {
  RefreshPage({Key key}) : super(key: key);

  @override
  _RefreshPageState createState() => _RefreshPageState();
}

class _RefreshPageState extends State<RefreshPage> {
  int intCount = 20;
  bool hasMore = true;
  bool isLoading = false;

  // 滚动控制器
  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    // 监听上滑事件，活动加载更多
    _scrollController.addListener(() {
      if (hasMore == false) return;
      // _scrollController.position.pixels 是当前像素点位置
      // _scrollController.position.maxScrollExtent 当前列表最大可滚动位置
      if (!isLoading &&
          _scrollController.position.pixels >=
              _scrollController.position.maxScrollExtent) {
        isLoading = true;
        setState(() {
          isLoading = true;
        });
        // 触发上拉加载更多机制
        _loadMore();
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    // 销毁 滚动控制器 ScrollController
    _scrollController.dispose();
    super.dispose();
  }

  // 上拉加载更多
  _loadMore() async {
    // 强制休眠 1 秒
    await Future.delayed(Duration(seconds: 2));

    // 更新 UI
    if (hasMore) {
      setState(() {
        isLoading = false;
        intCount += 20;
        if (intCount >= 90) {
          hasMore = false;
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("RefreshIndicator 示例"),
      ),
      body: Container(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 12.0),
          child: RefreshIndicator(
            onRefresh: _onRefresh,
            child: ListView.separated(
              scrollDirection: Axis.vertical,
              controller: _scrollController,
              shrinkWrap: true,
              itemCount: intCount + 1,
              itemBuilder: (BuildContext context, int position) {
                // print(position);
                if (position < intCount) {
                  return ListTile(
                    leading: Container(
                      width: 40,
                      height: 40,
                      decoration: BoxDecoration(
                        color: Colors.black12,
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                        // border: Border.all(color: Colors.cyan, width: 2.0),
                      ),
                      child: Icon(
                        Icons.person,
                      ),
                    ),
                    title: Text('ListTile'),
                    subtitle: Text(
                        'loading page ${position + 1}, isLoading $isLoading'),
                    // iconColor: Colors.blue,
                    trailing: Icon(Icons.chevron_right),
                  );
                }
                return CommonLoadingButton(
                    loadingState: isLoading, hasMore: hasMore);
              },
              separatorBuilder: (context, index) {
                return Divider(
                  thickness: 1.0,
                  height: 1.0,
                  color: Colors.deepOrange,
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  // 下拉刷新回调方法
  Future<Null> _onRefresh() async {
    // 强制休眠 1 秒
    await Future.delayed(Duration(seconds: 2));

    // 更新状态
    setState(() {
      hasMore = true;
      intCount = 20;
      isLoading = false;
    });
    return null;
  }
}
